﻿using Microsoft.Extensions.Logging;
using Quartz;

namespace DDD.BackgroundService.Jobs
{
    //https://www.dmoe.cc/random.php
    internal class DownloadImageJob : IJob
    {
        internal const string CRON = "0 0/1 * * * ? ";
        public const string CLIENT_NAME = "download_url";

        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<DownloadImageJob> _logger;

        public DownloadImageJob(IHttpClientFactory httpClientFactory, ILogger<DownloadImageJob> logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            var httpClient = _httpClientFactory.CreateClient(DownloadImageJob.CLIENT_NAME);
            var response = await httpClient.GetAsync("random.php");

            if (response.IsSuccessStatusCode)
            {
                var bytes = await response.Content.ReadAsByteArrayAsync();
                using var memoryStream = new MemoryStream(bytes);

                var date = DateTime.Now.Date;
                string basePath = Path.Combine("images", date.Year.ToString(), date.Month.ToString(), date.Day.ToString());
                if (!Directory.Exists(basePath))
                    Directory.CreateDirectory(basePath);

                memoryStream.Flush();
                memoryStream.Close();
                memoryStream.Dispose();
                File.WriteAllBytes($"{Path.Combine(basePath, Guid.NewGuid().ToString())}.jpg", bytes);
                _logger.LogInformation($"{DateTime.Now}定时任务执行成功");
            }

        }
    }
}
